/**
 * 
 */
package com.rangers.manage.email.handler;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.rangers.manage.email.config.EmailProperty;
import com.rangers.manage.email.config.EmailServerProperty;

/**
 * 邮箱服务provider
 * @author fuhw
 * @date 2017年10月25日
 */
public class EmailServerProvider {

	private Map<String, JavaMailSender> mailServerStore = new ConcurrentHashMap<>();

	private final EmailServerProperty emailProperty;
	
	public EmailServerProvider(EmailServerProperty emailProperty) {
		super();
		this.emailProperty = emailProperty;
		Map<String, EmailProperty> servers = emailProperty.getServers();
		Assert.isTrue(!CollectionUtils.isEmpty(servers), "the config of email server is null:请先配置邮箱服务器");
		servers.forEach((serverType, emailConfig) -> {
			this.init(serverType, emailConfig);
		});
	}

	public void init(String serverType, EmailProperty emailConfig) {

		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(emailConfig.getHost());
		mailSender.setUsername(emailConfig.getUsername());
		mailSender.setPassword(emailConfig.getPassword());
		mailSender.setDefaultEncoding("UTF-8");

		// smtp服务器验证
		Properties properties = new Properties();
		properties.put("mail.smtp.auth", Boolean.TRUE);// 设置需要身份认证
		properties.put("mail.smtp.starttls.enable", Boolean.TRUE); // 始终使用安全设置
		properties.put(" mtp.starttls.required", Boolean.TRUE); // 始终使用安全设置
		properties.put("mail.smtp.timeout", 25000); // 邮件超时时间
		mailSender.setJavaMailProperties(properties);
		mailServerStore.put(serverType, mailSender);
	}

	public JavaMailSender getByServerType(String serverType) {
		Assert.hasText(serverType, "the type of server cannot be null:配置服务的类型不能为空");
		return mailServerStore.get(serverType);
	}
	
	public EmailProperty getEmailConfig(String serverType) throws IllegalArgumentException {
		EmailProperty emailConfig = emailProperty.getServers().get(serverType);
		Assert.notNull(emailConfig, String.format("未获取到【%s】的服务配置信息", serverType));
		return emailConfig;
	}

}
